package com.huatai.exchange.deal;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.FileUtils;
import com.huatai.exchange.dal.model.ExcDataFileInfo;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.facade.FileSourceConstants;
import com.huatai.exchange.utils.VelocityContextHelper;
import com.huatai.exchange.utils.VelocityUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;
import java.util.UUID;

@Service("fileCreateVelocityDealService")
public class FileCreateVelocityDealServiceImpl extends AbstractFileCreateDealServiceImpl implements FileCreateDealService {

    @Autowired
    private VelocityContextHelper velocityHelper;

    @Override
    void generate(Map<String, Object> valueMap, ExcDataFileInfo dataFileInfo, StringBuffer fileNames, StringBuffer filePaths) throws BusinessException {
        String tmpFilePath = tmpFile + UUID.randomUUID().toString();
        File f = new File(tmpFilePath);
        try {
            String fileName = formatStr(dataFileInfo.getFileName(), valueMap);
            String veloContent = formatStr((String) valueMap.get(FileSourceConstants.VELOCITY_CONTENT), valueMap);
            Velocity.init();
            VelocityContext context = velocityHelper.fillContext(valueMap);
            String content = VelocityUtils.evaluate(context, veloContent);
            FileUtils.writeFile(f, content);
            // 文件中心  获取文件
            fileNames.append(",").append(fileName);
            String filePath = fileOperateService.uploadFile(f);
            filePaths.append(",").append(filePath);
            valueMap.put(Contents.FILE_GC, valueMap.get(Contents.FILE_GC) + "," + filePath);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }finally {
             f.deleteOnExit();
        }
    }
}
